<?php
    /* Fingon 2011.10 */
    require_once('global.php');
    require_once('/code/Include/db_mysql.php');
    require_once('/code/Include/thumb_handler.php');
    require_once('/code/SiteInfo.php');

    Class Product
    {
        protected $db;
        
        const IMG_MAX_W=600;
        const IMG_MAX_H=600;
        //const IMG_WATERMARK_FONTSIZE=20;
        const IMG_WATERMARK_OFFSET_X=15;
        const IMG_WATERMARK_OFFSET_Y=-10;
        const THUMB_MAX_W=190;
        const THUMB_MAX_H=170;
        //const THUMB_WATERMARK_FONTSIZE=5;
        const THUMB_WATERMARK_OFFSET_X=5;
        const THUMB_WATERMARK_OFFSET_Y=-5;
        const IMG_LOCATION='/gallery/images/';
        const IMG_THUMB_SUFFIX='thumb';
        //const WATERMARK_TEXT='© PhotoFromThe1st.com';
        const WATERMARK_FONT='./code/Include/ariblk.ttf';
        //const WATERMARK_PCT=20;

        public function Product()    {
            $this->db=new DB();
        }
        
        public function getProductsByCategory($cid, $active_only=1, $page=0, $count=0, $sort='order by create_time DESC')   {
            $sql='select product.*, artist.name, product_image.thumb_url from `product` left join `artist` on product.artist_id=artist.artist_id left join product_image on product_image.img_id=product.cover_img_id where exists(select 1 from product_category where product.product_id=product_category.product_id and product_category.category_id='.$cid.')'.($active_only ? ' && product.is_active = 1' : '').' '.$sort.($page*$count ? ' limit '.($page-1)*$count.','.$count : '');
            return $this->db->get_rows($sql);
        }
        
        public function getProductsByArtist($aid, $active_only=1, $page=0, $count=0, $sort='order by create_time DESC')   {
            $sql='select product.*, artist.name, product_image.thumb_url from `product` left join `artist` on product.artist_id=artist.artist_id left join product_image on product_image.img_id=product.cover_img_id where product.artist_id = '.$aid.($active_only ? ' && product.is_active = 1' : '').' '.$sort.($page*$count ? ' limit '.($page-1)*$count.','.$count : '');
            return $this->db->get_rows($sql);        
        }

        public function getProductByID($pid)    {
            $sql='select product.*, artist.name from `product` left join `artist` on product.artist_id=artist.artist_id where product_id = '.$pid;
            return $this->db->get_one($sql);
        }

        public function addProduct($p)    {            //无图片，全信息
            $p=$this->db->prepare_param($p);
            $sql=sprintf("insert into `product` (`subject`, `material`, `date`, `artist_id`, `code`, `location`, `intro`, `size`, `price`, `is_active`, `is_sold`, `create_time`) values ('%s', '%s', %s, %s, '%s', '%s', '%s', '%s', '%s', %s, %s, now())", $p['subject'], $p['material'], $p['date'], $p['artist_id'], $p['code'], $p['location'], $p['intro'], $p['size'], $p['price'], $p['is_active'], $p['is_sold']);
            $this->db->update($sql);
            $pid=$this->db->insert_id();
            $cid=$p['category_id'];
            $this->addProductCategory($pid, $cid);
            return $pid;
        }       
        
        public function getProductCategories($pid){
            $sql="select category.* from category where exists (select 1 from  product_category where product_category.product_id=$pid and product_category.category_id=category.category_id)";
            return $this->db->get_rows($sql);
        }
        
        public function getUnassignedCategories($pid){
            $sql="select category.* from category where not exists (select 1 from  product_category where product_category.product_id=$pid and product_category.category_id=category.category_id)";
            return $this->db->get_rows($sql);
        }
        
        public function addProductCategory($pid, $cid){
            $sql="insert ignore into product_category values($pid, $cid)";
            return $this->db->update($sql);
        }
        
        public function deleteProductCategory($pid, $cid){
            if ($this->countProductCategories($pid)<2) return -1;
            $sql="delete from product_category where product_id=$pid && category_id=$cid";
            return $this->db->update($sql);
        }
        
        public function countProductCategories($pid){
            $sql="select count(*) as item_count from product_category where product_id=$pid";
            $rs=$this->db->get_one($sql);
            return intval($rs['item_count']);
        }
        
        public function editProduct($p)    {
            $p=$this->db->prepare_param($p);
            $sql=sprintf("update `product` set `subject`='%s', `material`='%s', `date`='%s', `artist_id`=%s, `code`='%s', `location`='%s', `intro`='%s', `size`='%s', `price`='%s', `is_active`=%s, `is_sold`=%s where `product_id`=%s", $p['subject'], $p['material'], $p['date'], $p['artist_id'], $p['code'], $p['location'], $p['intro'], $p['size'], $p['price'], $p['is_active'], $p['is_sold'], $p['product_id']);
            return $this->db->update($sql); 
        }
        
/**
* 创建商品，并上传第一张图像，设为cover
* @param    array    $p     商品属性数组，包含category_id
* @param    uploaded_file    $imgFile     上传图片，$_FILES文件
*/
        public function createProduct($cid,$imgFile)    {            
            $tmp_url=$imgFile['tmp_name'];
            try{
                $url=$this->createGalleryImage($tmp_url);
            }
            catch(Exception $e){
                throw $e;
            }
            $pid=$this->addProductEmpty($cid);
            $sql="insert into product_image (`img_url`, `thumb_url`, `product_id`, `create_time`) values ('".$url['img_url']."', '".$url['thumb_url']."', '$pid', now())";
            $this->db->update($sql);
            $img_id=$this->db->insert_id();
            $this->setProductCoverImage($pid, $img_id);
            return $pid;
        }
                
        private function addProductEmpty($cid)    {
            $sql='insert into `product` (`create_time`) values (now())';
            $this->db->update($sql);
            $pid=$this->db->insert_id();
            $this->addProductCategory($pid, $cid);
            return $pid;
        } 
                
        private function createGalleryImage($tmp_url){
            $t=new ThumbHandler();
            $siteInfo=new SiteInfo();
            $w=$siteInfo->getWartermark();
            $t->setMaskWord($w['watermark_text']);
            $t->setMaskFont(self::WATERMARK_FONT);
            $t->setMaskTxtPct($w['watermark_transparency']);
            //image
            $t->setSrcImg($tmp_url);
            $img_url=self::IMG_LOCATION.$this->getRndFileName().'.'.$t->img_type;
            $t->setDstImg('.'.$img_url);
            $t->setMaskFontSize(intval($w['watermark_fontsize_img']));
            $t->setMaskOffsetX(self::IMG_WATERMARK_OFFSET_X);
            $t->setMaskOffsetY(self::IMG_WATERMARK_OFFSET_Y);
            $t->createImg(self::IMG_MAX_W,self::IMG_MAX_H);
            //thumb
            $t->setSrcImg($tmp_url);
            $thumb_url=self::IMG_LOCATION.$this->getRndFileName().'.'.$t->img_type;
            $t->setDstImg('.'.$thumb_url);
            $t->setMaskFontSize(intval($w['watermark_fontsize_thumb']));
            $t->setMaskOffsetX(self::THUMB_WATERMARK_OFFSET_X);
            $t->setMaskOffsetY(self::THUMB_WATERMARK_OFFSET_Y);
            try{$t->createImg(self::THUMB_MAX_W,self::THUMB_MAX_H);} catch(Exception $e){@unlink('.'.$img_url); throw $e;}
            @unlink($tmp_url);
            return array('img_url'=>$img_url, 'thumb_url'=>$thumb_url);
        }
        
        public function addGalleryImage($pid, $imgFile){
            $tmp_url=$imgFile['tmp_name'];
            try{
                $url=$this->createGalleryImage($tmp_url);
            }
            catch(Exception $e){
                throw $e;
            }
            $sql="select subject from product where product_id=$pid";
            $p=$this->db->get_one($sql);
            $sql="insert into product_image (`img_url`, `thumb_url`, `product_id`, `img_caption`, `create_time`) values ('".$url['img_url']."', '".$url['thumb_url']."', '$pid', '".$p['subject']."', now())";
            $this->db->update($sql);
            return $this->db->insert_id();
        }
        
        public function getProductGallery($pid){
            $sql="select product_image.*, !isnull(product.cover_img_id) as is_cover from product_image left join product on product_image.img_id=product.cover_img_id where product_image.product_id=$pid order by is_cover desc";
            return $this->db->get_rows($sql);
        }
        
        public function editGalleryImageInfo($i){
            $i=$this->db->prepare_param($i);
            $sql="update product_image set `img_caption`='".$i['img_caption']."', `img_descript`='".$i['img_descript']."' where img_id=".$i['img_id'];
            return $this->db->update($sql);
        }
        
        public function deleteGalleryImage($iid){
            //can not delete last img
            $sql="select count(*) as count from product_image where product_id=(select product_id from product_image where img_id=$iid)";
            $rs=$this->db->get_one($sql);
            if(intval($rs['count'])<2) return -1;
            //can not delete cover img
            $sql="select count(*) as count from product where cover_img_id=$iid";
            $rs=$this->db->get_one($sql);
            if(intval($rs['count'])>0) return -2;
            $sql="select `img_url`, `thumb_url` from product_image where `img_id`=$iid";
            $url=$this->db->get_one($sql);
            @unlink('.'.$url['img_url']);
            @unlink('.'.$url['thumb_url']);
            $sql="delete from product_image where img_id=$iid";
            return $this->db->update($sql);
        }
        
        public function countGalleryImages($pid){
            $sql="select count(*) as img_count from product_image where `product_id`=$pid";
            $rs=$this->db->get_one($sql);
            return intval($rs['img_count']);
        }
        
        public function setProductCoverImage($pid, $img_id){
            $sql="update product set `cover_img_id`=$img_id where `product_id`=$pid";
            return $this->db->update($sql);
        }
        
        public function getImage($iid){
            $sql="select *, (select cover_img_id from product where cover_img_id=$iid) as is_cover from product_image where `img_id`=$iid";
            return $this->db->get_one($sql);
        }

        public function deleteProduct($pid)    {   
            try{
                $this->deleteProductImages($pid);
                //$this->deleteProductCategories($pid);
                $sql="delete from product where product_id=$pid";
                $this->db->update($sql);
            }
            catch(Exception $e){throw $e;}
        }
        
        private function deleteProductCategories($pid){
            $sql="delete from product_category where product_id=$pid";
            return $this->db->update($sql);
        }
        
        private function deleteProductImages($pid){
            $sql="select `img_url`, `thumb_url` from product_image where `product_id`=$pid";
            $urls=$this->db->get_rows($sql);
            foreach($urls as $url){
                @unlink('.'.$url['img_url']);
                @unlink('.'.$url['thumb_url']);
            }
            //$sql="delete from product_image where product_id=$pid";
            //return $this->db->update($sql);
        }
        
        private function getRndFileName(){
            return date('YmdHis').rand(100,999);
        }
        
/**
* 按固定宽或高缩放图像，返回图像显示宽高
* @param    bool    $WorH     固定宽度0，固定高度1
* @param    int    $value     值
* @param    string    $img_url     图像文件URL
* @return    array    $newsize     像显示宽高
*/
        public function getImgResize($WorH, $value, $img_url){
            $size=getimagesize($img_url);
            $w=$size[0];$h=$size[1];
            if(!$WorH) {if($size[0]>$value) {$w=$value;$h=$size[1]*$value/$size[0];}}
            else{if($size[1]>$value) {$h=$value;$w=$size[0]*$value/$size[1];}}
            $size[0]=$w;$size[1]=$h;
            return $size;
        }
    }
?>